package com.hzj.rtsp.task;

import com.hzj.rtsp.service.AdminService;
import com.hzj.rtsp.dto.Video;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

/**
 * Created by Hzj on 2021/5/22.
 */
public class TaskMaager {

    static Map<String,HlsTasker> tasks = new ConcurrentHashMap<String,HlsTasker>();

    private static AdminService adminService;
    private static ThreadPoolTaskExecutor executor ;
    public static void createTask(String videoid,String m3u8path){
        if(!isContain(videoid)){
           if(adminService==null){
               adminService = SpringContextHolder.getBean(AdminService.class);
               executor = SpringContextHolder.getBean("asyncExecutor");
           }
            Video video = adminService.getVideoById(videoid);
            if(video!=null) {
               String url = VideoUtil.getRTSPUrl(video);
               HlsTasker tasker = new HlsTasker(video, url, m3u8path);
               Future future = executor.submit(tasker);
               tasks.put(videoid, tasker);
           }
        }else {

            tasks.get(videoid).reloadPlayTime();
        }
    }

    public static boolean isContain(String videoid){
        return tasks.containsKey(videoid);
    }
    public static void removeTask(String videoid){
        tasks.remove(videoid);
    }
}
